package job.job_0823;

public class BinarySearch {
    public static void main(String[] args) {
        int []arr={1,2,3,4,5,6,7};
        System.out.println("查找6");
        System.out.println("返回下标："+binarySearch(arr,6));
        System.out.println("查找9");
        System.out.println("返回下标："+binarySearch(arr,9));

    }
    public static int binarySearch(int[]arr,int find){//给定一个有序整型数组, 实现二分查找
        int left=0;
        int right=arr.length-1;
        int mid=left+((right-left)>>1);
        while(left<=right){
            if(arr[mid]<find){
                left=mid+1;
                mid=left+((right-left)>>1);
            }
            else if(arr[mid]>find){
                right=mid-1;
                mid=left+((right-left)>>1);
            }
            else{
                return mid;
            }
        }
        return -1;
    }
}
